import math

WIDTH = 300
HEIGHT = 300

BACK_COLOR = (0, 0, 127)
CIRCLE_COLOR = (0, 200, 0)

# 投影运算
def proj(a, b):
    proj_v = normalize(b[0], b[1])
    return dot(a, proj_v)

# 点乘运算
def dot(a, b):
    return a[0] * b[0] + a[1] * b[1]

def normalize(x, y):
    s = math.sqrt(x ** 2 + y ** 2)
    return x / s, y / s
class MyCircle:
    def __init__(self, x, y, r, dir_x, dir_y):
        self.x = x
        self.y = y
        self.r = r
        self.dir_x, self.dir_y = normalize(dir_x, dir_y)
        self.spd = 1

    def SetSpeed(self, spd):
        self.spd = spd

    def Update(self):
        self.x += self.dir_x * self.spd
        self.y += self.dir_y * self.spd

        bounce = False
        if self.x + self.r > WIDTH:
            self.x = WIDTH - self.r
            bounce = True
        
        if self.x - self.r < 0:
            self.x = self.r
            bounce = True
        
        if bounce == True:
            self.dir_x *= -1

        bounce = False

        if self.y + self.r > HEIGHT:
            self.y = HEIGHT - self.r
            bounce = True

        if self.y - self.r < 0:
            self.y = self.r
            bounce = True
        
        if bounce == True:
            self.dir_y *= -1
    
    def OnCollide(self, c):
        cdir_x = c.x - self.x
        cdir_y = c.y - self.y
        cdir_x, cdir_y = normalize(cdir_x, cdir_y)
        
        self.dir_x -= cdir_x
        self.dir_y -= cdir_y

        # self.dir_x += -cdir_x
        # self.dir_y += -cdir_y

        self.dir_x, self.dir_y = normalize(self.dir_x, self.dir_y)
        
    def Draw(self):
        screen.draw.filled_circle((self.x, self.y), self.r, CIRCLE_COLOR)

def on_key_down(key):
    if key == keys.ESCAPE:
        quit() 
        
def on_mouse_down(pos):
    print("mouse_down", pos)
    
def on_mouse_up(pos):
    print("mouse_up", pos)

c1 = MyCircle(50, 50, 30, 3, 1)
c2 = MyCircle(50, 250, 30, 1, -2)
c3 = MyCircle(250, 50, 30, 3, 1)
c4 = MyCircle(250, 250, 30, 1, -2)
c5 = MyCircle(150, 150, 30, 3, 1)

c1.SetSpeed(2)
c2.SetSpeed(2)
c3.SetSpeed(2)
c4.SetSpeed(2)
c5.SetSpeed(2)

c_list = []
c_list.append(c1)
c_list.append(c2)
c_list.append(c3)
c_list.append(c4)
c_list.append(c5)

def CheckCollision(c1, c2):
    if math.sqrt((c1.x - c2.x) ** 2 + (c1.y - c2.y) ** 2) <= c1.r + c2.r:
        c1.OnCollide(c2)
        c2.OnCollide(c1)

def update():
    global c_list
    for c1 in c_list:
        for c2 in c_list:
            if c1 != c2:
                CheckCollision(c1, c2)

    for c in c_list:
        c.Update()
        
def draw():
    global c_list
    screen.clear()
    screen.fill(BACK_COLOR)

    for c in c_list:
        c.Draw()

